package com.gis.halodepok;

import java.util.Arrays;
import java.util.Comparator;

import android.content.Context;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class AdapterItem extends ArrayAdapter<Item> {

	Item[] list;
	Location currentlocation;

	public Item[] getList() {
		return list;
	}

	Context parent;

	public AdapterItem(Context context, int textViewResourceId, Item[] list,
			Location currentlocation) {
		super(context, textViewResourceId, list);

		this.list = list;
		this.parent = context;
		this.currentlocation = currentlocation;
	}

	public void sortByNameAsc() {

		Comparator<Item> comparator = new Comparator<Item>() {
			@Override
			public int compare(Item object1, Item object2) {
				try {
					float a = currentlocation.distanceTo(object1.getLocation());
					float b = currentlocation.distanceTo(object2.getLocation());
					return (int) (a - b);
				} catch (NullPointerException e) {
					return 0;
				}
			}
		};
		Arrays.sort(list, comparator);
		notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		LayoutInflater inflater = (LayoutInflater) this.parent
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.list, parent, false);
		TextView v1 = (TextView) view.findViewById(R.id.nama);
		TextView v2 = (TextView) view.findViewById(R.id.alamat);
		TextView v3 = (TextView) view.findViewById(R.id.telp);
		TextView v4 = (TextView) view.findViewById(R.id.jarak);
		Item depok = list[position];
		v1.setText(depok.getNama());
		v2.setText(depok.getAlamat());
		v3.setText(depok.getTelp());
		if (currentlocation != null && depok.getLocation() != null) {
			double jarak = currentlocation.distanceTo(depok.getLocation());
			v4.setText(String.format("%.3f Km", jarak / 1000));
		} else {
			v4.setText("None");
		}

		return view;
	}
	
	

}
